#include "mainwindow.h"
#include "iconstyleitemdelegate.h"
#include "ui_mainwindow.h"

#include <QClipboard>
#include <QDebug>
#include <QDesktopServices>
#include <QDir>
#include <QImageReader>
#include <QKeyEvent>
#include <QMessageBox>
#include <QMimeData>
#include <QScrollBar>
#include <QStandardPaths>
#include <QStringListModel>
#include <QUrl>
#include <dbusutil.h>

#ifdef Q_OS_LINUX
#define EMOJI_RECV_PATH "nt_data/Emoji/emoji-recv"
#endif

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    initializeUI();
    loadEmojiData();
}

MainWindow::~MainWindow()
{
    delete ui;
}

// [1] 处理UI初始化
void MainWindow::initializeUI()
{
    setWindowTitle("主窗口");
    ui->statusbar->showMessage("数量多加载会慢 - 一旦加载完成请避免调整窗口大小 - 双击可复制图片");

    ui->listView->setModel(&m_model);
    ui->listView->setViewMode(QListView::IconMode);

    ui->listView->setSpacing(5);
    ui->listView->setEditTriggers(QAbstractItemView::NoEditTriggers);

    IconStyleItemDelegate *delegate = new IconStyleItemDelegate(this);
    ui->listView->setItemDelegate(delegate);

    // 连接更新请求
    connect(delegate, &IconStyleItemDelegate::requestUpdate, this, [this](const QModelIndex &index){
        ui->listView->update(index);
    });
    // 更新可见区域
    connect(ui->listView->verticalScrollBar(), &QScrollBar::valueChanged, this, [this, delegate](){
        delegate->setViewVisibleRect(ui->listView->viewport()->rect());
    });
    // 初始可见区域设置
    delegate->setViewVisibleRect(ui->listView->viewport()->rect());

    // 连接右键请求
    connect(delegate, &IconStyleItemDelegate::rightClicked, this, &MainWindow::slotListItemRightClicked);

    connect(ui->listView, &QListView::doubleClicked, [this, delegate](const QModelIndex &index){
        // Q_EMIT ui->listView->edit(index); // 这会触发createEditor调用
        const QString filePath = index.data(990).toString();

        if (filePath.isEmpty()) {
            qDebug() << "Empty file path";
            return nullptr;
        }

        // 根据文件类型调用不同的复制方法
        if (delegate->isActuallyGif(filePath)) {
            copyAnimatedGifToClipboard(filePath);
        } else {
            copyImageToClipboard(filePath);
        }

        qDebug() << "Copied:" << filePath;
        return nullptr; // 返回nullptr表示我们不创建实际的编辑器
    });
}

void MainWindow::slotListItemRightClicked(const QModelIndex &index, const QPoint &globalPos)
{

    // 获取文件路径 (假设存储在990角色)
    QString filePath = index.data(990).toString();
    qDebug() << "Right-clicked on:" << filePath;

    // 创建右键菜单
    QMenu menu;

    QAction *copyAction = menu.addAction("复制");
    QAction *openAction = menu.addAction("打开文件");
    QAction *openLocationAction = menu.addAction("打开所在位置");
    menu.addSeparator();
    QAction *propertiesAction = menu.addAction("属性");

    // 显示菜单并获取选择
    QAction *selectedAction = menu.exec(globalPos);

    if (selectedAction == copyAction) {
        // 处理复制操作
        if (filePath.endsWith(".gif", Qt::CaseInsensitive)) {
            copyAnimatedGifToClipboard(filePath);
        } else {
            QApplication::clipboard()->setPixmap(QPixmap(filePath));
        }
        ui->statusbar->showMessage("已复制到剪贴板", 2000);
    }
    else if (selectedAction == openAction) {
        // 处理打开操作
        QDesktopServices::openUrl(QUrl::fromLocalFile(filePath));
    }
    else if (selectedAction == openLocationAction) {
        // 处理打开位置操作
        DBusUtil::showFileLocation(index.data(990).toString());
    }
    else if (selectedAction == propertiesAction) {
        // 显示文件属性
        showFileProperties(filePath);
    }

//    menu.exec(QCursor::pos());
}

// [2] 加载emoji数据的主流程
void MainWindow::loadEmojiData()
{
    const QString qqConfigPath = QStandardPaths::writableLocation(QStandardPaths::HomeLocation)
                                    + QDir::separator() + ".config/QQ";

    QDir qqDir(qqConfigPath);
    if (!qqDir.exists()) {
        return;
    }

    const auto qqEntries = qqDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
    for (const auto& entry : qqEntries) {
        if (entry.fileName().startsWith("nt_qq_")) {
            ui->cb_account->addItem(entry.fileName(), entry.filePath());
        }
    }
}

// [3] 处理单个QQ账号目录
void MainWindow::processQQAccount(const QFileInfo &accountDir)
{
    QDir emojiDir(accountDir.absoluteFilePath());
    if (!emojiDir.cd(EMOJI_RECV_PATH)) {
        return;
    }

    QStringList emojiPaths;
    const auto monthDirs = emojiDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
    for (const auto& monthDir : monthDirs) {
        QDir oriDir(monthDir.absoluteFilePath());
        if (oriDir.cd("Ori")) {
            const auto emojiFiles = oriDir.entryInfoList(QDir::Files);
            for (const auto& emojiFile : emojiFiles) {
                emojiPaths << emojiFile.absoluteFilePath();
            }
        }
    }

    if (!emojiPaths.isEmpty()) {
        addAccountToList(accountDir.fileName(), emojiPaths);
    }
}

// [4] 将账号添加到列表控件
void MainWindow::addAccountToList(const QString &accountName, const QStringList &emojiPaths)
{
    QStringList emojis = emojiPaths;
    qDebug() << emojis;

    foreach (auto emoji, emojis) {
        QStandardItem *var = new QStandardItem;
        var->setData(emoji, 990);
        m_model.appendRow(var);
    }
    emit m_model.layoutChanged();
}

void MainWindow::copyImageToClipboard(const QString &filePath)
{
    QClipboard *clipboard = QApplication::clipboard();
    QPixmap pixmap(filePath);

    if (!pixmap.isNull()) {
        clipboard->setPixmap(pixmap);
    } else {
        qDebug() << "Failed to load image:" << filePath;
    }
}

void MainWindow::copyAnimatedGifToClipboard(const QString &filePath)
{
    QClipboard* clipboard = QApplication::clipboard();
    QMimeData* mimeData = new QMimeData();

    // 读取GIF文件内容
    QFile file(filePath);
    if (file.open(QIODevice::ReadOnly)) {
        QByteArray gifData = file.readAll();
        file.close();

        // 设置GIF数据
        mimeData->setData("image/gif", gifData);
        mimeData->setUrls({QUrl::fromLocalFile(filePath)});

        // 同时设置第一帧作为静态图像，提高兼容性
        QImageReader reader(filePath);
        QImage image = reader.read();
        if (!image.isNull()) {
            mimeData->setImageData(image);
        }

        clipboard->setMimeData(mimeData);
    } else {
        qDebug() << "Failed to open GIF file:" << filePath;
        delete mimeData;
    }
}

void MainWindow::showFileProperties(const QString &filePath)
{
    QFileInfo info(filePath);
    QString message = QString("文件名: %1\n大小: %2 KB\n创建时间: %3")
                          .arg(info.fileName())
                          .arg(info.size() / 1024)
                          .arg(info.created().toString("yyyy-MM-dd HH:mm:ss"));

    QMessageBox::information(this, "文件属性", message);
}

void MainWindow::resizeEvent(QResizeEvent *event)
{
    mediawiki_search_timer.stop();
    mediawiki_search_timer.disconnect();
    mediawiki_search_timer.setInterval(1000);

    connect(&mediawiki_search_timer, &QTimer::timeout, this, [this]()
            {
                mediawiki_search_timer.stop();
                emit m_model.layoutChanged();
            });

    mediawiki_search_timer.start();
}

void MainWindow::keyPressEvent(QKeyEvent *event)
{
    if (event->type() == QEvent::KeyPress) {
        if (event->key() == Qt::Key_Escape) {
            showMinimized();
            return;
        }
    }

    QMainWindow::keyPressEvent(event);
}

void MainWindow::on_lineEdit_textChanged(const QString &arg1)
{
    QDir dir(arg1);
    QStringList filelist;
    QFileInfoList infolist = dir.entryInfoList(QDir::NoDotDot | QDir::NoDot | QDir::Files);

    for (int i = 0; i < infolist.size(); i++)
    {
        auto info = infolist[i];
        qDebug() << info.path();
        auto suffix = info.suffix();
        // QFileInfoList tempList = currentDir.entryInfoList(fileList, QDir::Files);
        auto avaliable = [ = ]
        {
            return
                suffix.indexOf("jpg") == 0 ||
                suffix.indexOf("jpeg") == 0 ||
                suffix.indexOf("png") == 0 ||
                suffix.indexOf("svg") == 0 ||
                suffix.indexOf("gif") == 0 ;
        };
        if (avaliable())
        {
            filelist << info.filePath();
            // qDebug() << info.path();
        }
    }

    foreach (auto emoji, filelist) {
        QStandardItem *var = new QStandardItem;
        var->setData(emoji, 990);
        m_model.appendRow(var);
    }

    qDebug() << filelist.count();
    emit m_model.layoutChanged();
}


void MainWindow::on_cb_account_currentIndexChanged(int index)
{
    if (index!=0) {
        QFileInfo entry(ui->cb_account->currentData().toString());
        processQQAccount(entry);
    }
}

